package chaw.android.train;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import chaw.android.util.HttpRequestManager;
import chaw.android.util.LoadBitMap;
import chaw.android.util.Preferences;
import chaw.android.util.SeparatedListAdapter;
import chaw.android.util.ServerURL;

import android.app.ActivityGroup;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FavoritePeopleListActivity extends ListActivity implements OnGestureListener{
	private ArrayList<JSONObject> json_list;
	private ArrayList<PeopleItem> list, list2;
	private PeopleItemAdapter nadapter, nadapter2;
	private GestureDetector gesture;
	private String json_modify;
	private String fling = "";
	
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		gesture = new GestureDetector(this);
		json_modify = "";
        setContentView(R.layout.favorite_people_list);
	    list = new ArrayList<PeopleItem>();
	    list2 = new ArrayList<PeopleItem>();
	    json_list = new ArrayList<JSONObject>();   
		View lv = getListView();
		lv.setOnTouchListener(new View.OnTouchListener() {
		    @Override
			public boolean onTouch(View v, MotionEvent event) {
		    	if(gesture.onTouchEvent(event)){
		    		if(fling.equals("right")){
		            	ActivityGroup parentActivity = (ActivityGroup) getParent();
		    			((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("FavoritePageList",
		    						new Intent(getBaseContext(),FavoritePageListActivity.class));
		    		}
		    		else if(fling.equals("left")){
		            	ActivityGroup parentActivity = (ActivityGroup) getParent();
		    			((FavoriteActivity) parentActivity).startChildActivityWithoutCurrentActivity("FavoriteStationList",
		    						new Intent(getBaseContext(),FavoriteStationListActivity.class));
		    		}
		    	}
		    	return gesture.onTouchEvent(event);
		    }
		}); 
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setListView();
	}
	
	private void setListView(){
		DownloadAsynkTask task = new DownloadAsynkTask();
		String[] params = new String[]{ ServerURL.favoritePeople, "user_id", Preferences.getValue(getBaseContext(), "user_id")};
		task.execute(params);
	}

	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
			
			if(urls.length > 1)
				for(int i = 1; i< urls.length; i+=2)
					params.add(new BasicNameValuePair(urls[i], urls[i+1]));
			response = HttpRequestManager.request(urls[0], params);
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			json_modify = result;
			list.clear();
			list2.clear();
			DownloadAsynkTask2 task = new DownloadAsynkTask2();
			task.execute(new String[]{result});
		}
	}
	private class DownloadAsynkTask2 extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			String response = null;
			JSONObject json_obj;
			try {
				json_obj = new JSONObject(urls[0]);
				JSONArray json_arr = (JSONArray) json_obj.get("users");
				JSONArray json_arr2 = (JSONArray) json_obj.get("users_from");
				json_list.add(new JSONObject());
				for(int i = 0 ; i < json_arr.length(); i++){
					JSONObject users = (JSONObject) json_arr.get(i);
					Bitmap image = null;
					if(!users.get("image_thumb_url").toString().equals("null") && !users.get("image_thumb_url").toString().equals("")){
						image = LoadBitMap.fromURL(users.get("image_thumb_url").toString());
					}
					list.add(new PeopleItem(users.get("nick_name").toString(), image));
					json_list.add(users);
				}	
				json_list.add(new JSONObject());
				for(int i = 0 ; i < json_arr2.length(); i++){
					JSONObject users = (JSONObject) json_arr2.get(i);
					Bitmap image = null;
					if(!users.get("image_thumb_url").toString().equals("null") && !users.get("image_thumb_url").toString().equals("")){
						image = LoadBitMap.fromURL(users.get("image_thumb_url").toString());
					}
					list2.add(new PeopleItem(users.get("nick_name").toString(), image));
					json_list.add(users);
				}	
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
	        SeparatedListAdapter adapter = new SeparatedListAdapter(getBaseContext(), R.layout.favorite_people_header, R.id.content);
	          
			nadapter = new PeopleItemAdapter(getBaseContext(), R.layout.favorite_people_row, list);
			nadapter2 = new PeopleItemAdapter(getBaseContext(), R.layout.favorite_people_row, list2);  
	        adapter.addSection("내가 좋아하는 사람", nadapter);  
	        adapter.addSection("나를 좋아하는 사람", nadapter2);  
		    ListView lv = getListView();
		    lv.setAdapter(adapter);
		}
	}


	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		try {
			JSONObject output = json_list.get(position);
			String out = (String)output.get("user_id");
			ActivityGroup parentActivity = (ActivityGroup) getParent();
			Intent intent = new Intent(getBaseContext(), EachProfileActivity.class);
			intent.putExtra("user_id", out);
			((FavoriteActivity) parentActivity).startChildActivity("EachProfile", intent);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		
	}

    @Override
	public boolean onTouchEvent(MotionEvent me) {
        return gesture.onTouchEvent(me);
    }
	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		// TODO Auto-generated method stub
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            
            // right to left swipe
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	fling = "right";
        		return true;
            }
            // left to right swipe
            else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	fling = "left";
        		return true;
            }
            else{
            	return false;
            }
        } catch (Exception e) {
    		return false;
            
        }
 
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(0, 1 , 0 , "친구 관리");
		menu.add(0, 2 , 0 , "차단 관리");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case 1:
			if(!json_modify.equals("")){
				Intent intent = new Intent(getBaseContext(), ModifyPeopleListActivity.class);
				intent.putExtra("modify_list", json_modify);
				startActivity(intent);
				return true;
			}
			else{
				return false;
			}
		case 2:
			if(!json_modify.equals("")){
				Intent intent = new Intent(getBaseContext(), DenyPeopleListActivity.class);
				intent.putExtra("modify_list", json_modify);
				startActivity(intent);
				return true;
			}
			else{
				return false;
			}
		}
		return false;
	}

	private class PeopleItemAdapter extends ArrayAdapter<PeopleItem>{
		private ArrayList<PeopleItem> items;
		private int layout;
		
		public PeopleItemAdapter(Context ctx, int rsrcId, ArrayList<PeopleItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
			this.layout = rsrcId;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(layout, null);
			}
			PeopleItem e = items.get(position);
			if(e != null){

				ImageView image = ((ImageView)v.findViewById(R.id.userPic));
				if(e.getImage() != null ){
					image.setImageBitmap(e.getImage());
				}
				((TextView)v.findViewById(R.id.favorite_user_id)).setText(e.getName());
			}
			return v;
		}
	}
	
	public class PeopleItem{
		private String nick_name;
		private Bitmap image_url;
		
		private PeopleItem(String name, Bitmap image){
			nick_name = name;
			image_url = image;
		}
		private String getName(){
			return nick_name;
		}
		private Bitmap getImage(){
			return image_url;
		}
	}
	
}
